package com.sg.business.management.handler;

import java.util.Iterator;
import java.util.Map;

import org.eclipse.core.commands.Command;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.IWorkbenchPart;

import com.mobnut.db.model.IContext;
import com.mobnut.db.model.ModelService;
import com.mobnut.db.model.PrimaryObject;
import com.sg.business.model.DocumentDefinition;
import com.sg.business.model.DummyModel;
import com.sg.widgets.command.AbstractNavigatorHandler;
import com.sg.widgets.part.CurrentAccountContext;
import com.sg.widgets.part.editor.DataObjectDialog;
import com.sg.widgets.viewer.ViewerControl;

public class SetDocumentType extends AbstractNavigatorHandler {

	@Override
	protected void execute(PrimaryObject selected, IWorkbenchPart part,
			ViewerControl vc, Command command, Map<String, Object> parameters,
			IStructuredSelection selection) {
		if (selection == null || selection.isEmpty()) {
			return;
		}
		DummyModel po = ModelService.createModelObject(DummyModel.class);
		try {
			DataObjectDialog openDialog = DataObjectDialog.openDialog(po,
					"editor.documentDefinition.documenttype", true, null);
			if (openDialog.getReturnCode() == DataObjectDialog.OK) {
				IContext context = new CurrentAccountContext();
				Object documentType = po
						.getValue(DocumentDefinition.F_DOCUMENT_TYPE);
				if (documentType != null) {
					Iterator<?> iter = selection.iterator();
					while (iter.hasNext()) {
						Object value = iter.next();
						if (value instanceof DocumentDefinition) {
							DocumentDefinition docDef = (DocumentDefinition) value;
							docDef.setValue(DocumentDefinition.F_DOCUMENT_TYPE,
									documentType);
							docDef.doSave(context);
						}
					}
					vc.doRefresh();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
